<template>
    <el-dialog class="config-dialog" title="模型数据库配置" width="55%" :visible="visible"
               append-to-body @close="handleClose" @closed="$emit('input', false)">

        <el-form ref="form" :model="config" :rules="rules" size="mini" label-width="150px">
            <el-form-item label="配置名称：" prop="name">
                <el-input class="input" v-model.trim="config.name" :disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item label="数据库地址：" prop="host">
                <el-input class="input" v-model.trim="config.host"></el-input>
            </el-form-item>
            <el-form-item label="数据库用户名：" prop="user">
                <el-input class="input" v-model.trim="config.user"></el-input>
            </el-form-item>
            <el-form-item label="数据库密码：" prop="password">
                <el-input class="input" v-model.trim="config.password"></el-input>
            </el-form-item>
        </el-form>

        <div slot="footer">
            <el-button :loading="saveLoading" @click="handleClose">取 消</el-button>
            <el-button type="success" :loading="saveLoading" @click="saveClick">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script type="text/ecmascript-6">
  import rules from "./rules";
  import R from "../../../res/R";
  import { local } from "../../../utils/js/storage";
  import { MODEL } from "../../../res/config-key";

  /**
   * @author 白雨浓
   * @date 2019/7/7 12:06
   *
   * 配置窗口
   **/
  export default {
    name: 'ConfigDialog',
    props: ['value', 'type', 'configName'],
    data() {
      return {
        visible: this.value,
        saveLoading: false,
        rules: rules(this),
        config: {},
        configs: [],
      }
    },
    created() {
      const configs = local.getItem(MODEL.CONFIG);

      if (!configs) {
        return;
      }

      this.configs = configs;

      if (this.type === R.dialog.EDIT) {
        this.config = configs.find(item => item.name === this.configName);
      }
    },
    computed: {
      disabled() {
        return this.type === R.dialog.EDIT;
      }
    },
    methods: {
      async saveClick() {
        await this.$valid(this);

        if (this.type === R.dialog.EDIT) {
          const index = this.configs.findIndex(item => item.name === this.configName);
          this.configs.splice(index, 1);
        }

        if (this.config.host.includes(':')) {
          const ss = this.config.host.split(':');
          this.config.host = ss[0];
          this.config.port = ss[1];
        }

        this.configs.push(this.config);
        local.setItem(MODEL.CONFIG, this.configs);

        this.$emit('submit');
        this.handleClose();
      },
      handleClose() {
        this.visible = false;
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
    .config-dialog {
    }

    .input {
        width 90%
    }
</style>
